// lib/scenes/scene_01_single_insert.dart
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';


class Scene01SingleInsert extends StatefulWidget {
  const Scene01SingleInsert({super.key});
  @override
  State<Scene01SingleInsert> createState() => _Scene01SingleInsertState();
}

class _Scene01SingleInsertState extends State<Scene01SingleInsert>
    implements DeltaTextInputClient {
  late final TextInputConnection _conn;
  TextEditingValue _value = const TextEditingValue(text: '');
  final List<String> _logs = [];

  /* === DeltaTextInputClient 完整实现 === */
  @override
  TextEditingValue get currentTextEditingValue => _value;

  @override
  void updateEditingValueWithDeltas(List<TextEditingDelta> deltas) {
    print("单字符 updateEditingValueWithDeltas---->${deltas}");
    _logs.add('updateEditingValueWithDeltas');
    for (final delta in deltas) {
      print(
          "DeLTA TEST ===> updateEditingValueWithDeltas  start ${delta.selection.start}");
      print(
          "DeLTA TEST ===> updateEditingValueWithDeltas  end ${delta.selection.end}");
      if (delta is TextEditingDeltaInsertion) {

        _logs.add('单字符插入: "${delta.textInserted}" 位置=${delta.selection.start}');
      }
    }
    setState(() {
      for (final d in deltas) _value = d.apply(_value);
    });
  }
  /* 其余空实现，保证零报错 */
  @override
  void updateEditingValue(TextEditingValue value) {
    _logs.add('updateEditingValue');

  }
  @override
  void performAction(TextInputAction action) {
    _logs.add('performAction');

  }
  @override
  void connectionClosed() {
    _logs.add('connectionClosed');
  }

  @override
  void insertContent(KeyboardInsertedContent content) {
    _logs.add('insertContent');
  }
  @override
  void insertTextPlaceholder(Size size) {
    _logs.add('insertTextPlaceholder');
  }
  @override
  void performPrivateCommand(String action, Map<String, dynamic> data) {
    _logs.add('performPrivateCommand');
  }
  @override
  void performSelector(String selectorName) {
    _logs.add('performSelector');
  }
  @override
  void removeTextPlaceholder() {
    _logs.add('removeTextPlaceholder');
  }
  @override
  void showAutocorrectionPromptRect(int start, int end) {
    _logs.add('showAutocorrectionPromptRect');
  }
  @override
  void showToolbar() {
    _logs.add('showToolbar');
  }
  @override
  void updateFloatingCursor(RawFloatingCursorPoint point) {
    _logs.add('updateFloatingCursor');
  }


  /* === 生命周期 === */
  @override
  void initState() {
    super.initState();
    _conn = TextInput.attach(
      this,
      const TextInputConfiguration(enableDeltaModel: true),
    )
      ..show()
      ..setEditingState(_value);
  }

  @override
  void dispose() {
    _conn.close();
    super.dispose();
  }

  /* === UI === */
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('单字符插入 Delta 场景')),
      body: Column(
        children: [
          Expanded(
            child: ListView.builder(
              padding: const EdgeInsets.all(8),
              itemCount: _logs.length,
              itemBuilder: (_, i) => Text(_logs[i],
                  style: const TextStyle(fontSize: 12, fontFamily: 'monospace')),
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(12),
            child: TextField(
              controller: TextEditingController.fromValue(_value),
              decoration: const InputDecoration(
                hintText: '逐字输入，观察 Delta',
                border: OutlineInputBorder(),
              ),
              onChanged: (_) {},
            ),
          ),
        ],
      ),
    );
  }

  @override
  // TODO: implement currentAutofillScope
  AutofillScope? get currentAutofillScope => throw UnimplementedError();

  @override
  void didChangeInputControl(TextInputControl? oldControl, TextInputControl? newControl) {
    // TODO: implement didChangeInputControl
  }
}